package com.hyy.book2.service;

import com.hyy.book2.mapper.BookMapper;
import com.hyy.book2.model.BookInfo;
import com.hyy.book2.model.BookStatusEnum;
import com.hyy.book2.model.PageRequest;
import com.hyy.book2.model.PageResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.awt.print.Book;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class BookService {
    @Autowired
    private BookMapper bookMapper;

    public String InsertBook(BookInfo bookInfo) {
        try {
            int result = bookMapper.insertBook(bookInfo);
            if (result == 1) return "";//插入成功
        } catch (Exception e) {
            log.error("数据库插入图书信息失败，e{}", e);
        }
        return "数据插入失败，请联系管理员。";
    }

    public PageResponse<BookInfo> getListByPage(PageRequest pageRequest) {
        int offset = pageRequest.getOffset();
        int limit = pageRequest.getPageSize();
        int count = bookMapper.getCount();

        log.info("数据库查询偏移量，{} 数量,{}",offset,limit);
        List<BookInfo> books = bookMapper.queryBookPage(offset, limit);

        //赋值状态字符转
        for(BookInfo bookInfo : books) {
            bookInfo.setStatusCN(BookStatusEnum.getStatusByCode(bookInfo.getStatus()).getDesc());
        }
        return new PageResponse<BookInfo>(count,books,pageRequest);
    }

        //更新图书
        public String updateBook(BookInfo bookInfo) {
                try{
                    int result=bookMapper.updateBook(bookInfo);//影响行数大于0，更新成功
                    if(result>0)return "";
                    else return "数据库没有进行更新";
                }catch (Exception e){
                    log.info("数据库更新失败抛出异常：{}",e);
                    return "数据库更新失败";
                }
        }

    public BookInfo queryBookById(Integer bookId) {
            return bookMapper.queryBookByID(bookId);
    }

    public String deleteBookById(Integer bookId) {
        List<Integer> list=new ArrayList<>();
        list.add(bookId);
        Integer result;
        try{
            result=bookMapper.batchDelete(list);
        }catch (Exception e){
            log.info("数据库删除失败:{}",e);
            return "数据库删除失败";
        }

        if(result>0){
            return "";
        }else {
            return "未成功删除图书，数据库未报错";
        }
    }
    public String batchDelete(List<Integer> ids) {
        Integer result=0;
        try{
                result=bookMapper.batchDelete(ids);
            }catch (Exception e){
                log.error("数据库批量删除失败：{}",e);
            }
        if(result>0)return "";
        return "未成功删除";
    }
}
